//
//  FileUtil.swift
//  Jock
//
//  Created by HD on 15/3/14.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

class FileUtil {
    
    // 文件是否存在
    class func fileExist(path: String) -> Bool {
        return NSFileManager.defaultManager().fileExistsAtPath(path)
    }
    
    // 新建缓存文件夹
    class func createCacheDirectory(dirName: String) -> Bool {
        let arr =  NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
        let path = arr[0] as! String
        let diskCachePath = path.stringByAppendingPathComponent(dirName)
        if !NSFileManager.defaultManager().fileExistsAtPath(diskCachePath) {
            NSFileManager.defaultManager().createDirectoryAtPath(diskCachePath, withIntermediateDirectories: true, attributes: nil, error: nil)
            return true
        }
        return false
    }
    
    // 获取缓存路径
    class func getCachePath(dirName: String, fileName: String) -> String {
        var arr =  NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
        var path = arr[0] as! String
        createCacheDirectory(dirName)
        return "\(path.stringByAppendingPathComponent(dirName))/\(fileName)"
    }
    
    // 读取路径为UIImage
    class func loadImageFromPath(path: String) -> UIImage! {
        var exist = NSFileManager.defaultManager().fileExistsAtPath(path)
        if exist {
            return UIImage(contentsOfFile: path)!
        }
        return nil
    }
    
    // 保存图片到缓存
    class func imageCacheToPath(path: String, image: NSData) -> Bool {
        return image.writeToFile(path, atomically: true)
    }
}